<template>
  <t-modal
    :title="filterTitle()"
    width="1048px"
    :visible="visible"
    @ok="onSubmit()"
    @cancel="closeModal()"
    wrapClassName="add-modal-container"
    forceRender
    v-bind:confirmLoading="confirmLoading"
    v-bind="footer"
  >
    <div class="curve-modal-body">
      <a-form-model
        ref="ruleForm"
        :model="form"
        :rules="rules"
        :hideRequiredMark="isDisabled"
      >
        <div class="sub-title">基本信息</div>
        <a-form-model-item label="任务名称">
          <a-input v-model="form.name" disabled> </a-input>
        </a-form-model-item>
        <a-row :gutter="0">
          <a-col :span="12">
            <a-form-model-item label="节点等级">
              <a-select style="width: 100%" v-model="form.nodeLevel" disabled>
                <a-select-option
                  :value="item.dicItemCode"
                  v-for="item in nodeLevelSource"
                  :key="item.uuid"
                >
                  {{ item.dicItemName }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="节点类型">
              <a-select style="width: 100%" v-model="form.nodeType" disabled>
                <a-select-option
                  :value="item.dicItemCode"
                  v-for="item in nodeTypeSource"
                  :key="item.uuid"
                >
                  {{ item.dicItemName }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row :gutter="0">
          <a-col :span="12">
            <a-form-model-item label="计划开始时间">
              <a-date-picker
                disabled
                style="width: 100%"
                v-model="form.planStartTime"
                format="YYYY-MM-DD"
                valueFormat="YYYY-MM-DD"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="计划结束时间">
              <a-date-picker
                disabled
                style="width: 100%"
                v-model="form.planEndTime"
                format="YYYY-MM-DD"
                valueFormat="YYYY-MM-DD"
              />
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row :gutter="0">
          <a-col :span="12">
            <a-form-model-item label="周期">
              <a-input v-model="form.duration" disabled> </a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="关键节点">
              <a-radio-group v-model="form.major" disabled>
                <a-radio :value="1"> 是 </a-radio>
                <a-radio :value="2"> 否 </a-radio>
              </a-radio-group>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row :gutter="0">
          <a-col :span="12">
            <a-form-model-item label="采购方式" prop="procurementMethod">
              <a-select
                style="width: 100%"
                v-model="form.procurementMethod"
                placeholder="请选择"
              >
                <a-select-option
                  :value="item.dicItemCode"
                  v-for="item in purchaseModeSource"
                  :key="item.uuid"
                >
                  {{ item.dicItemName }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="招标金额" prop="tenderAmount">
              <a-input-number
                v-model="form.tenderAmount"
                placeholder="请输入"
              />
              <span class="page-unit">万元</span>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-form-model-item label="招标单位" prop="tenderUnit">
          <a-input v-model="form.tenderUnit" placeholder="请输入"></a-input>
        </a-form-model-item>
        <a-row :gutter="0">
          <a-col :span="12">
            <a-form-model-item label="计划发标时间" prop="planIssuanceTime">
              <a-date-picker
                :disabled="isDisabled"
                style="width: 100%"
                v-model="form.planIssuanceTime"
                format="YYYY-MM-DD"
                valueFormat="YYYY-MM-DD"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item
              label="计划定标发布时间"
              prop="planCalibrationTime"
            >
              <a-date-picker
                :disabled="isDisabled"
                style="width: 100%"
                v-model="form.planCalibrationTime"
                format="YYYY-MM-DD"
                valueFormat="YYYY-MM-DD"
              />
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-form-model-item label="文件">
          <bjUploadFile
            :count="20"
            v-model="form.tenderFiles"
            @preview="viewFile($event)"
            @download="downloadFile($event)"
            @change="handleUpLoadFile($event, 'tenderFiles')"
            :replaceFields="{
              fileName: 'fileName',
              fileSize: 'fileSize',
              fileType: 'fileType',
            }"
          ></bjUploadFile>
        </a-form-model-item>
        <a-row :gutter="0">
          <a-col :span="12">
            <a-form-model-item label="实际开始时间" prop="actualStartTime">
              <a-date-picker
                :disabled="isDisabled"
                style="width: 100%"
                v-model="form.actualStartTime"
                format="YYYY-MM-DD"
                valueFormat="YYYY-MM-DD"
                :disabled-date="disabledStartDate"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="实际结束时间" prop="actualEndTime">
              <a-date-picker
                :disabled="isDisabled"
                style="width: 100%"
                v-model="form.actualEndTime"
                format="YYYY-MM-DD"
                valueFormat="YYYY-MM-DD"
                :disabled-date="disabledEndDate"
                @change="endDateChange()"
              />
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row :gutter="0">
          <a-col :span="12">
            <a-form-model-item label="完成状态">
              <a-select v-model="form.status" style="width: 100%" disabled>
                <a-select-option :value="1">
                  提前完成
                </a-select-option>
                <a-select-option :value="2">
                  正常完成
                </a-select-option>
                <a-select-option :value="3">
                  延期完成
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="偏差天数">
              <a-input v-model="form.deviationDays" disabled> </a-input>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-form-model-item label="偏差原因" prop="deviationReason">
          <a-textarea
            :rows="4"
            placeholder="请输入"
            v-model="form.deviationReason"
          />
        </a-form-model-item>
        <a-form-model-item label="成果文件">
          <bjUploadFile
            :count="20"
            v-model="form.files"
            @preview="viewFile($event)"
            @download="downloadFile($event)"
            @change="handleUpLoadFile($event, 'files')"
            :replaceFields="{
              fileName: 'fileName',
              fileSize: 'fileSize',
              fileType: 'fileType',
            }"
          ></bjUploadFile>
        </a-form-model-item>
        <a-form-model-item label="工作范围">
          <a-textarea
            :rows="4"
            placeholder="请输入"
            v-model="form.scopeOfWork"
          />
        </a-form-model-item>
        <a-form-model-item label="备注" prop="remark">
          <a-textarea :rows="4" placeholder="请输入" v-model="form.remark" />
        </a-form-model-item>
        <div class="sub-title">2 前置任务</div>
        <vxe-table
          ref="xTable"
          border="inner"
          align="center"
          max-height="400"
          :data="form.frontList"
          :column-config="{ resizable: true }"
          :scroll-y="{ enabled: true }"
          :scroll-x="{ enabled: true }"
          :loading="loading"
          :row-config="{ keyField: 'uuid' }"
        >
          <vxe-column type="seq" width="80" title="序号"></vxe-column>
          <vxe-column field="sourceTaskName" title="合同名称" min-width="300">
          </vxe-column>
          <vxe-column field="type" title="类型"> </vxe-column>
          <vxe-column field="duration" title="间隔时间(天)"> </vxe-column>
        </vxe-table>
      </a-form-model>
    </div>
    <!-- 附件预览弹窗 -->
    <previewModal
      ref="previewModal"
      :visible.sync="previewModal.visible"
      :loading="previewModal.loading"
    ></previewModal>
  </t-modal>
</template>

<script>
import { mapGetters } from "vuex";
import moment from "moment";
import { axios } from "@/utils/request";
import { getToken, downloadDfs } from "@/utils/TopVUI";
//附件
import bjUploadFile from "@/components/extendCustom/bj-upload-file";
//预览
import previewModal from "@/pages/document/minio/previewModal";
import { getDicItemByCode } from "@/api/common.js";
import { getContractByProCode } from "@/api/cantonManage";
import {
  getFillReportDetail,
  getConfigDetail,
  getConfigDetailDraft,
  getConfigDetailHistory,
  saveFillReport,
} from "@/api/progressManage";
export default {
  inject: ["versionSource"],
  components: {
    bjUploadFile,
    previewModal,
  },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    operateType: {
      type: [String, Number],
      default: "",
    },
    parameter: {
      type: Object,
      default: () => {
        return {};
      },
    },
  },
  data() {
    return {
      isDisabled: false,
      confirmLoading: false,
      footer: {},
      form: {
        uuid: "",
        //任务名称
        name: "",
        //周期
        duration: "",
        //节点等级
        nodeLevel: undefined,
        //节点类型
        nodeType: undefined,
        //计划开始时间
        planStartTime: "",
        //计划结束时间
        planEndTime: "",
        //重大里程碑
        major: "",
        //前置任务
        frontList: [],
        //采购方式
        procurementMethod: undefined,
        //合同类型
        contractType: undefined,
        //实际开始时间
        actualStartTime: "",
        //实际完成时间
        actualEndTime: "",
        //完成状态
        status: "",
        //偏差天数
        deviationDays: "",
        //偏差原因
        deviationReason: "",
        //备注
        remark: "",
        //成果文件
        files: [],
        //工作范围
        scopeOfWork: "",
        //招标金额
        tenderAmount: "",
        //招标单位
        tenderUnit: "",
        //计划发标时间
        planIssuanceTime: "",
        //计划定标发布时间
        planCalibrationTime: "",
        //文件
        tenderFiles: [],
      },
      rules: {
        actualStartTime: [
          {
            required: true,
            message: "请输入实际开始时间",
          },
        ],
        actualEndTime: [
          {
            required: true,
            message: "请输入实际完成时间",
          },
        ],
        deviationReason: [
          {
            required: true,
            message: "请输入偏差原因",
          },
        ],
        procurementMethod: [
          {
            required: true,
            message: "请选择采购方式",
          },
        ],
        contractType: [
          {
            required: true,
            message: "请选择合同类型",
          },
        ],
        tenderAmount: [
          {
            required: true,
            message: "请输入招标金额",
          },
        ],
        tenderUnit: [
          {
            required: true,
            message: "请输入招标单位",
          },
        ],
        planIssuanceTime: [
          {
            required: true,
            message: "请选择计划发标时间",
          },
        ],
        planCalibrationTime: [
          {
            required: true,
            message: "请选择计划定标发布时间",
          },
        ],
      },
      loading: false,
      //节点类型
      nodeTypeSource: [],
      //节点等级
      nodeLevelSource: [],
      //采购方式
      purchaseModeSource: [],
      //预览
      previewModal: {
        visible: false,
        loading: false,
      },
    };
  },
  computed: {
    ...mapGetters(["configData"]),
    kkFileView() {
      let index = this.configData.findIndex(
        (item) => item.code === "kkFileView"
      );
      if (index >= 0) {
        return this.configData[index].value;
      } else {
        return "http://192.168.1.216:8012/onlinePreview";
      }
    },
  },
  watch: {
    visible: {
      handler(val) {
        if (val) {
          this.getData();
        }
      },
      immediate: true,
    },
  },
  methods: {
    //查询数据
    async getData() {
      //查询节点类型
      this.nodeTypeSource = await this.getDicCodeData("scheduleType");
      //查询节点等级
      this.nodeLevelSource = await this.getDicCodeData("nodeLevel");
      //采购方式
      this.purchaseModeSource = await this.getDicCodeData("procurementMethod");
      //详情
      await this.getDetail();
      //填报详情
      await this.getFillDetail();
    },

    getConfigDetail,
    getConfigDetailDraft,
    getConfigDetailHistory,
    //详情
    getDetail() {
      return new Promise((resolve, reject) => {
        let { status = "" } = this.versionSource();
        let { uuid, proCode } = this.parameter;
        let apiUrl = "";
        if (status == 4) {
          //正式
          apiUrl = "getConfigDetail";
        } else if (status == 5) {
          //历史
          apiUrl = "getConfigDetailHistory";
        } else {
          //草稿
          apiUrl = "getConfigDetailDraft";
        }
        this[apiUrl]({
          uuid,
          proCode,
        })
          .then((res) => {
            let { data } = res;
            //任务名称
            this.form.name = data?.name;
            //节点等级
            this.form.nodeLevel = data?.nodeLevel;
            //节点类型
            this.form.nodeType = data?.nodeType;
            //周期
            this.form.duration = data?.duration;
            //计划开始时间
            this.form.planStartTime = data?.planStartTime;
            //计划结束时间
            this.form.planEndTime = data?.planEndTime;
            //重大里程碑
            this.form.major = data?.major;
            //前置任务
            this.form.frontList = data?.predecessorList ?? [];
            //实际开始时间
            this.form.actualStartTime = data?.actualStartTime;
            //实际结束时间
            this.form.actualEndTime = data?.actualEndTime;
            resolve();
          })
          .catch((_) => {
            reject();
          });
      });
    },
    //填报详情
    getFillDetail() {
      return new Promise((resolve, reject) => {
        let { uuid, proCode } = this.parameter;
        getFillReportDetail({ itemId: uuid, proCode })
          .then((res) => {
            let { data } = res;
            //数据id
            this.form.uuid = data?.uuid;
            //完成状态
            this.form.status = data?.status;
            //偏差天数
            this.form.deviationDays = data?.deviationDays;
            //偏差原因
            this.form.deviationReason = data?.deviationReason;
            //采购方式
            this.form.procurementMethod = data?.procurementMethod ?? undefined;
            //备注
            this.form.remark = data?.remark;
            //成果文件
            this.form.files = JSON.parse(data?.files ?? "[]");
            //工作范围
            this.form.scopeOfWork = data?.scopeOfWork;
            //招标金额
            this.form.tenderAmount = data?.tenderAmount;
            //招标单位
            this.form.tenderUnit = data?.tenderUnit;
            //计划发标时间
            this.form.planIssuanceTime = data?.planIssuanceTime;
            //计划定标发布时间
            this.form.planCalibrationTime = data?.planCalibrationTime;
            //文件
            this.form.tenderFiles = JSON.parse(data?.tenderFiles ?? "[]");
            resolve();
          })
          .catch((_) => {
            reject();
          });
      });
    },
    //下载
    downloadFile(row) {
      let { url } = row;
      if (!url) {
        this.$message.success("文件不存在", 1.5);
        return;
      }
      downloadDfs(url);
    },
    //预览
    viewFile(file) {
      let { url } = file;
      this.previewModal.loading = true;
      this.$refs.previewModal.type = "file";
      this.$refs.previewModal.fileUrl =
        this.kkFileView +
        "/onlinePreview?url=" +
        encodeURIComponent(Base64.encode(url)) +
        "&watermarkTxt=" +
        //水印内容
        encodeURIComponent("") +
        "&token=" +
        getToken();
      this.previewModal.visible = true;
      this.previewModal.loading = false;
    },

    //上传附件
    handleUpLoadFile({ file, index }, domain) {
      let formData = new FormData();
      formData.append("bucket", "yx-cloud-vue");
      formData.append("file", file);
      this.$set(this.form[domain][index], "loading", true);
      axios
        .post(`/document/minio/uploadfile`, formData, {
          headers: {
            "Content-Type": "multipart/form-data",
          },
        })
        .then((res) => {
          this.$set(this.form[domain][index], "dfsFileUuid", res.dfsFileUuid);
          this.$set(this.form[domain][index], "url", res.url);
        })
        .catch((_) => {
          this.$set(this.form[domain][index], "fail", true);
        })
        .finally((_) => {
          this.$set(this.form[domain][index], "loading", false);
        });
    },

    //查询字典表
    getDicCodeData(dicCode = "") {
      return new Promise((resolve, reject) => {
        getDicItemByCode({ code: dicCode })
          .then((res) => {
            let { data } = res;
            resolve(data);
          })
          .catch((_) => {
            reject();
          })
          .finally((_) => {});
      });
    },

    //确定
    onSubmit() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          let { form, parameter } = this;
          //成果文件
          const files_1 = form.files.map(
            ({ $$DataType, file, loading, ...keepAttrs }) => keepAttrs
          );
          //文件
          const files_2 = form.tenderFiles.map(
            ({ $$DataType, file, loading, ...keepAttrs }) => keepAttrs
          );
          let formJson = {
            //项目名称
            proCode: parameter.proCode,
            //主键id
            itemId: parameter.uuid,
            //实际开始时间
            actualStartTime: form.actualStartTime,
            //实际完成时间
            actualEndTime: form.actualEndTime,
            //完成状态
            status: form.status,
            //偏差天数
            deviationDays: form.deviationDays,
            //偏差原因
            deviationReason: form.deviationReason,
            //备注
            remark: form.remark,
            //成果文件
            files: JSON.stringify(files_1),
            //采购方式
            procurementMethod: form.procurementMethod,
            //工作范围
            scopeOfWork: form.scopeOfWork,
            //招标金额
            tenderAmount: form.tenderAmount,
            //招标单位
            tenderUnit: form.tenderUnit,
            //计划发标时间
            planIssuanceTime: form.planIssuanceTime,
            //计划定标发布时间
            planCalibrationTime: form.planCalibrationTime,
            //文件
            tenderFiles: JSON.stringify(files_2),
          };
          if (form.uuid) {
            formJson.uuid = form.uuid;
          }
          this.confirmLoading = true;
          saveFillReport(formJson)
            .then((res) => {
              if (res.statusCode === 200 || res === 1) {
                this.closeModal();
                this.$message.success("操作成功", 1.5);
                this.$emit("success");
              } else {
                this.$message.error(res?.message ?? "操作失败");
              }
            })
            .catch((_) => {
              this.$message.error(_?.message ?? "操作失败");
            })
            .finally((_) => {
              this.confirmLoading = false;
            });
        }
      });
    },

    //重置表单
    resetForm() {
      this.form = {
        uuid: "",
        //任务名称
        name: undefined,
        //周期
        duration: "",
        //节点等级
        nodeLevel: undefined,
        //节点类型
        nodeType: undefined,
        //计划开始时间
        planStartTime: "",
        //计划结束时间
        planEndTime: "",
        //采购方式
        procurementMethod: undefined,
        //合同类型
        contractType: undefined,
        //重大里程碑
        major: "",
        //前置任务
        frontList: [],
        //实际开始时间
        actualStartTime: "",
        //实际完成时间
        actualEndTime: "",
        //完成状态
        status: "",
        //偏差天数
        deviationDays: "",
        //偏差原因
        deviationReason: "",
        //备注
        remark: "",
        //成果文件
        files: [],
      };
      this.$refs.ruleForm.resetFields();
    },

    //关闭弹窗
    closeModal() {
      this.resetForm();
      this.$emit("update:visible", false);
    },

    //完成状态
    compareDates(date1, date2) {
      const d1 = new Date(date1);
      const d2 = new Date(date2);
      if (d1 < d2) {
        return 3;
      } else if (d1 > d2) {
        return 1;
      } else {
        return 2;
      }
    },

    getDaysBetween(startDate, enDate) {
      const sDate = Date.parse(startDate);
      const eDate = Date.parse(enDate);
      const days = (eDate - sDate) / (1 * 24 * 60 * 60 * 1000);
      return days;
    },

    //实际结束时间
    endDateChange() {
      let { form } = this;
      let days = this.getDaysBetween(form.planEndTime, form.actualEndTime);
      if (days || days == 0) {
        this.form.deviationDays = Math.abs(days);
      } else {
        this.form.deviationDays = "";
      }
      //
      if (form.actualEndTime) {
        this.form.status = this.compareDates(
          form.planEndTime,
          form.actualEndTime
        );
      } else {
        this.form.status = "";
      }
    },

    disabledStartDate(current) {
      let startTime = moment(this.form.actualEndTime).valueOf();
      let currentTime = current.valueOf();
      return currentTime > startTime;
    },

    disabledEndDate(current) {
      let endTime = moment(this.form.actualStartTime).valueOf();
      let currentTime = current.valueOf();
      return currentTime < endTime;
    },

    filterTitle() {
      return "填报";
    },
  },
};
</script>

<style lang="less" scoped>
/deep/.add-modal-container {
  .ant-modal-body {
    padding: 0 !important;
  }
  .curve-modal-body {
    padding: 14px 70px 14px 14px;
    box-sizing: border-box;
    max-height: 700px;
    overflow: hidden;
    overflow-y: auto;
    .ant-form-item {
      display: flex;
      .ant-form-item-label {
        flex-shrink: 0;
        width: 140px;
      }
      .ant-form-item-control-wrapper {
        flex: 1;
        overflow: hidden;
      }
      .page-unit {
        position: absolute;
        right: 30px;
        font-size: 14px;
        color: #8a8a8c;
      }
    }
    .bj-upload-file {
      .choosed-file-warp {
        width: 100%;
      }
    }

    .sub-title {
      padding-left: 30px;
      font-family: Microsoft YaHei;
      font-weight: 400;
      font-size: 18px;
      color: #525a5d;
      position: relative;
      margin-bottom: 10px;
      display: flex;
      align-items: center;
      justify-content: space-between;
      &::after {
        content: "";
        width: 3px;
        height: 16px;
        background: #1890ff;
        position: absolute;
        left: 14px;
        top: 50%;
        transform: translateY(-50%);
      }
      .ant-btn {
        margin-right: 0;
      }
    }
  }
}
</style>
